﻿using Abp.Domain.Repositories;
using MyCompanyName.AbpZeroTemplate.Prm.Admin;
using MyCompanyName.AbpZeroTemplate.Prm.Project;
using MyCompanyName.AbpZeroTemplate.Prm.Topic.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyCompanyName.AbpZeroTemplate.Prm.Topic
{
    public class TopicAppService : AbpZeroTemplateAppServiceBase, ITopicAppService
    {

        private readonly ProjectManager projectManager;
        private readonly IRepository<TopicAttachment> topicAttachmentRepository;
        private readonly MailManager mailManagerRepository;
        private readonly OperationLogManager operationLogManager;

        public TopicAppService(ProjectManager _projectManager, IRepository<TopicAttachment> _topicAttachmentRepository,
         OperationLogManager _operationLogManager,
            MailManager _mailManagerRepository)
        {
            projectManager = _projectManager;
            topicAttachmentRepository = _topicAttachmentRepository;
            mailManagerRepository = _mailManagerRepository;
            operationLogManager = _operationLogManager;
        }
        /// <summary>
        /// 添加项目提问
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task CreateTopic(CreateTopicInPut input)
        {
            var topicId = projectManager.topicRepository.InsertAndGetId(new Project.Topic
            {
                Category = "",
                Content = input.Content,
                ProjectId = input.ProjectId,
                Title = input.Title
            });

            foreach (var item in input.UploadFile)
            {
                await topicAttachmentRepository.InsertAsync(new TopicAttachment()
               {
                   Extension = item.Extension,
                   FullPath = item.FullPath,
                   HostId = topicId,
                   Name = item.Name,
                   Size = item.Size,
                   TopicHost = TopicHost.提问
               });
            }

            await operationLogManager.Create(input.ProjectId, "项目问题提问",
                HostOperation.项目,
                Newtonsoft.Json.JsonConvert.SerializeObject(new { ProjectId = input.ProjectId, Title = input.Title }));


            #region 项目问题提问
            var projectInfo = projectManager.projectRepository.Get(input.ProjectId);
            var user = UserManager.Users.Where(x => x.Id == AbpSession.UserId.Value).FirstOrDefault();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic["项目名称"] = projectInfo.ProjectName;
            dic["项目编号"] = projectInfo.ProjectNo;
            dic["产品号"] = projectInfo.ProductNo;
            dic["操作时间"] = DateTime.Now.ToString("yyyy-MM-dd");
            dic["操作人"] = user.Name;
            dic["标题"] = input.Title;
            dic["内容"] = input.Content;
            mailManagerRepository.CreateMailRecord(dic, MailCatelog.项目问题提问, input.ProjectId);
            #endregion


        }


        /// <summary>
        /// 获取项目提问
        /// </summary>
        public List<GetTopicOutPut> GetTopic(int projectId)
        {
            List<GetTopicOutPut> result = new List<GetTopicOutPut>();
            var topics = projectManager.topicRepository.GetAll().Where(x => x.ProjectId == projectId).ToList();
            foreach (var item in topics)
            {
                var user = UserManager.Users.Where(x => x.Id == item.CreatorUserId).SingleOrDefault();
                var outPut = new GetTopicOutPut()
                {
                    Id = item.Id,
                    Content = item.Content,
                    Title = item.Title,
                    CreateOn = item.CreationTime.ToString("yyyy-MM-dd"),
                    CreateBy = user == null ? "未知" : user.UserName,
                    UploadFile = topicAttachmentRepository.GetAll().Where(x => x.HostId == item.Id && x.TopicHost == TopicHost.提问).ToList().Select(x => new Document.Dto.GetUploadFileOutPut()
                    {
                        Extension = x.Extension,
                        Path = x.FullPath,
                        Size = x.Size.ToString(),
                        Name = x.Name
                    }).ToList()
                };
                result.Add(outPut);
            }
            return result;
        }


        public List<GetTopicReplyOutPut> GetTopicReply(int topicId)
        {
            List<GetTopicReplyOutPut> result = new List<GetTopicReplyOutPut>();
            var replys = projectManager.replyRepository.GetAll().Where(x => x.TopicId == topicId).ToList();
            foreach (var item in replys)
            {
                var user = UserManager.Users.Where(x => x.Id == item.CreatorUserId).SingleOrDefault();
                var outPut = new GetTopicReplyOutPut()
                {
                    Content = item.Content,
                    CreateBy = user == null ? "未知" : user.UserName,
                    CreateOn = item.CreationTime.ToString("yyyy-MM-dd"),
                    UploadFile = topicAttachmentRepository.GetAll().Where(x => x.HostId == item.Id && x.TopicHost == TopicHost.回复).ToList().Select(x => new Document.Dto.GetUploadFileOutPut()
                    {
                        Extension = x.Extension,
                        Path = x.FullPath,
                        Size = x.Size.ToString(),
                        Name = x.Name
                    }).ToList()
                };
                result.Add(outPut);
            }
            return result;
        }
        public int GetTopicCount(int projectId)
        {
            return projectManager.topicRepository.GetAll().Where(x => x.ProjectId == projectId).Count();
        }
        public int GetTopicCount(int projectId, DateTime dts)
        {
            return projectManager.topicRepository.GetAll().Where(x => x.ProjectId == projectId && x.CreationTime >= dts).Count();
        }

        public async Task CreateTopicReply(CreateTopicReplyInPut input)
        {
            var replyId = projectManager.replyRepository.InsertAndGetId(new Reply()
            {
                Content = input.Content,
                TopicId = input.TopicId
            });
            foreach (var item in input.UploadFile)
            {
                await topicAttachmentRepository.InsertAsync(new TopicAttachment()
                {
                    Extension = item.Extension,
                    FullPath = item.FullPath,
                    HostId = replyId,
                    Name = item.Name,
                    Size = item.Size,
                    TopicHost = TopicHost.回复
                });
            }


            #region 项目问题解答
            var topic = projectManager.topicRepository.Get(input.TopicId);
            var projectInfo = projectManager.projectRepository.Get(topic.ProjectId);
            var user = UserManager.Users.Where(x => x.Id == AbpSession.UserId.Value).FirstOrDefault();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic["项目名称"] = projectInfo.ProjectName;
            dic["项目编号"] = projectInfo.ProjectNo;
            dic["产品号"] = projectInfo.ProductNo;
            dic["操作时间"] = DateTime.Now.ToString("yyyy-MM-dd");
            dic["操作人"] = user.Name;
            dic["标题"] = topic.Title;
            dic["内容"] = topic.Content;
            dic["回答"] = input.Content;
            mailManagerRepository.CreateMailRecord(dic, MailCatelog.项目问题解答, topic.ProjectId);
            #endregion



            await operationLogManager.Create(topic.ProjectId, "项目问题回答",
                HostOperation.项目,
                Newtonsoft.Json.JsonConvert.SerializeObject(new { ProjectId = topic.ProjectId, Title = topic.Title }));
        }
    }
}
